package com.makerworks.medu;

import android.animation.Animator
import android.animation.AnimatorSet
import android.animation.ObjectAnimator
import android.content.Context
import android.util.AttributeSet
import android.widget.ImageView

/**
 * Created by xuexin on 2016/9/7.
 */
class AlphaAnimationImageView : ImageView {

    private var sleepTime: Long = 0
    private var periodTime: Long = 0
    private var delayTime: Long = 0
    private val hideAnimator = ObjectAnimator.ofFloat(this, "alpha", 0f, 0f)
    private val alphaAnimator = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f)
    private val sleepAnimator = ObjectAnimator.ofFloat(this, "alpha", 1f, 1f)
    private var animSet: AnimatorSet? = null

    constructor(context: Context, attrs: AttributeSet) : super(context, attrs) {
        init(context, attrs, 0)
    }

    constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) {
        init(context, attrs, defStyleAttr)
    }


    private fun init(context: Context, attrs: AttributeSet, defStyleAttr: Int) {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.AlphaAnimationImageView)
        delayTime = typedArray.getInt(R.styleable.AlphaAnimationImageView_delay_time, 0).toLong()
        periodTime = typedArray.getInt(R.styleable.AlphaAnimationImageView_period_time, 0).toLong()
        sleepTime = typedArray.getInt(R.styleable.AlphaAnimationImageView_sleep_time, 0).toLong()
        typedArray.recycle()

        hideAnimator.duration = delayTime
        alphaAnimator.duration = periodTime
        sleepAnimator.duration = sleepTime
////        animator = {
//            var alphaAnimator = ObjectAnimator.ofFloat(this, "alpha", 0f, 1f)
//            AnimatorSet().playSequentially()
////        }

//        animator.duration = periodTime
//        animator.startDelay = delayTime
//        startAnimation()
    }


    //lyh 现在遇到一个问题,view没有事件监听自己是否可见,而这里的动画需要在可见的时候重置,所以作为方法来调用
    fun startAnimation() {
        alpha = 0f
        animSet = AnimatorSet()
        animSet?.playSequentially(hideAnimator, alphaAnimator, sleepAnimator)
//        animSet.play(hideAnimator).after(alphaAnimator).after(sleepAnimator)
        animSet?.addListener(object : Animator.AnimatorListener {
            override fun onAnimationRepeat(animation: Animator?) {
            }

            override fun onAnimationEnd(animation: Animator?) {
                if (isShown) {
                    animSet?.start()
                }
            }

            override fun onAnimationCancel(animation: Animator?) {
            }

            override fun onAnimationStart(animation: Animator?) {
            }

        })
        animSet?.start()
//        if (animator.isRunning) {
//            animator.end()
//        }
//
//        animator.start()
    }

    fun stopAnimation() {
        animSet?.cancel()
    }
}
